package com.aio;

import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements
        CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {

    @Override
    public void completed(AsynchronousSocketChannel channel, AsyncTimeServerHandler attachment) {
        try {
            AsyncTimeServerHandler.channel = channel;
            channel.setOption(StandardSocketOptions.TCP_NODELAY, true);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            channel.read(byteBuffer, byteBuffer, new ReadCompletionHandler(channel));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //继续监听连接请求
            attachment.getServerSocketChannel().accept(attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        attachment.getLatch().countDown();
    }

}
